<?php
namespace sm_shop\model;
use sm_shop\model;
class cronModel extends model{

    public static function add( $data ){

        global $_W;
        $now = date('Y-m-d H:i:s');
        $cycle = !empty( $data['cycle'] )? $data['cycle'] : 'day';
        $data = [
            'uniacid'=> $_W['uniacid'],
            'customer_id'=> $data['customer_id'],
            'name'=>$data['name'],
            'type'=>$data['type'],
            'type_value'=>$data['type_value'],
            'times'=>$data['times'],
            'cycle'=> $cycle,
            'extra'=> !empty( $data['extra'] )? $data['extra'] : '',
            'created_at'=> $now,
            'updated_at'=>$now,

        ];
        if( $cycle == 'day'){
            $data['day'] = !empty( $data['day'] )? $data['day'] : 1;
        }
        sm_pdo_insert( 'sh_cron', $data );
    }

    /**
     * @param $data
     * 记录 计划任务执行
     */
    public static function record( $data ){

        global $_W;
        $now = date('Y-m-d H:i:s');
        $data = [
            'uniacid'       => $_W['uniacid'],
            'customer_id'   => $data['customer_id'],
            'cron_id'       => $data['cron_id'],
            'created_at'    => $now
        ];

        if( sm_pdo_insert( 'cron_record', $data ) ){
            self::increase( $data['cron_id'] );
        }

    }


    /**
     * 增加计划任务执行次数
     */
    public static function increase( $cron_id ){

        $sql = 'update sh_cron set execution_times=execution_times+1 '
            . ' where id= "' . $cron_id . '"';
        sm_pdo_run( $sql );
    }

    public static function get_list(){


        $arr = [
            'status=1',
            'execution_times < times'
        ];
        $condition = implode(' and ', $arr);

        return sm_pdo_getall('cron', $condition );
    }

}
